import requests
import json

def list_elasticsearch_indices():
    """
    列出 Elasticsearch 中的全部索引
    """
    try:
        # 使用 cat indices API 获取索引列表
        response = requests.get('http://172.16.12.149:9200/_cat/indices?format=json&v=true', timeout=10)

        if response.status_code == 200:
            indices_data = response.json()
            print("Elasticsearch 索引列表:")
            print("-" * 80)

            # 表头
            print(f"{'health':<8} {'status':<8} {'index':<30} {'docs.count':<12} {'store.size':<10}")
            print("-" * 80)

            # 索引信息
            for index_info in indices_data:
                health = index_info.get('health', 'N/A')
                status = index_info.get('status', 'N/A')
                index_name = index_info.get('index', 'N/A')
                docs_count = index_info.get('docs.count', 'N/A')
                store_size = index_info.get('store.size', 'N/A')

                print(f"{health:<8} {status:<8} {index_name:<30} {docs_count:<12} {store_size:<10}")

        else:
            print(f"请求失败，状态码: {response.status_code}")
            print(f"响应内容: {response.text}")

    except requests.exceptions.ConnectionError:
        print("无法连接到 Elasticsearch 服务器")
    except requests.exceptions.Timeout:
        print("请求超时")
    except Exception as e:
        print(f"获取索引列表时发生错误: {e}")

if __name__ == "__main__":
    list_elasticsearch_indices()
